package com.example.bookmanage.result;

import com.example.bookmanage.enums.ResultCode;
import lombok.Data;

@Data
public class Result<T> {
    private int code;

    private String msg;

    private T data;

    public static <T> Result<T> success() {
        return assembleResult(null, ResultCode.SUCCESS);
    }

    public static <T> Result<T> success(T data) {
        return assembleResult(data, ResultCode.SUCCESS);
    }

    public static <T> Result<T> fail() {
        return assembleResult(null, ResultCode.FAILED);
    }

    /**
     * 自定义错误码
     */
    public static <T> Result<T> fail(ResultCode resultCode) {
        return assembleResult(null, resultCode);
    }

    /**
     * 自定义错误码和错误信息
     */
    public static <T> Result<T> fail(int code, String msg) {
        return assembleResult(code, msg);
    }

    /**
     * 封装返回结果
     */
    private static <T> Result<T> assembleResult(T data, ResultCode resultCode) {
        Result<T> result = new Result<>();
        result.setData(data);
        result.setCode(resultCode.getCode());
        result.setMsg(resultCode.getMsg());
        return result;
    }

    private static <T> Result<T> assembleResult(int code, String msg) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setData(null);
        result.setMsg(msg);
        return result;
    }
}
